博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django不用在数据库中创建新的user表而使用它的后台管理功能
阅读量:2432 次
发布时间:2019-05-10

本文共 6015 字,大约阅读时间需要 20 分钟。

在一个项目中经常要对远端的一个数据库中的数据做修改,每次都写sql感觉很麻烦,就想到能不能直接利用django的后台管理功能呢,当然是可以的,但是要登录django的后台使用它的管理功能必须在对应的数据库创建django后台管理需要的user和Log相关的表,而这个又是不可能的,那能不能不创建user表而仅仅是使用它的后台管理功能呢,答案是可以的

django后台登录需要输入用户名、密码,用户登录验证的backend默认是django.contrib.auth.backends,而它采用的是数据库表的验证,为了不创建新表,我们需要修改登录验证的backends,

修改的方法很简单,在setting.py中添加配置

AUTHENTICATION_BACKENDS = ["houtai.extend.auth.backends.SimpleBackend"]#用户验证的Backend
然后要实现SimpleBackend,验证后需要返回一个User对象,所以还需要实现一个SingleUser类

from __future__ import unicode_literalsfrom houtai.extend.auth.user import SingleUserclass SimpleBackend(object):    """    Authenticates against settings.AUTH_USER_MODEL.    """    def authenticate(self, username=None, password=None):        cur_user = SingleUser()        if cur_user.validate(username,password):            return cur_user            def get_user(self, user_id):        return SingleUser()
from houtai.extend.common import Singletonclass SingleUser(Singleton):    username = "admin"    password = "111111"    is_active = 1    is_staff =1    is_superuser =1    pk = '123456'           def validate(self,username,password):        if username and password:            if username == self.username and password == self.password:                return True        return False    def save(self,update_fields=['last_login']):        return    def has_module_perms(self, app_label):        """        Returns True if the user has any permissions in the given app label.        Uses pretty much the same logic as has_perm, above.        """        # Active superusers have all permissions.        if self.is_active and self.is_superuser:            return True        return False    def has_perm(self, perm, obj=None):        return True
有了上面的backends就能够用admin:111111登录到后台,单很快就会出现下面这个错误:

"Table 'test.django_content_type' doesn't exist"
这时候需要做下面三件事才能搞定:

1、修改admin后台首页的模板:

在url.py中添加admin.site.index_template = 'houtai/index.html'

index.html

{% extends "admin/base_site.html" %}{% load i18n admin_static %}{% block extrastyle %}{
{ block.super }}
{% endblock %}{% block coltype %}colMS{% endblock %}{% block bodyclass %}dashboard{% endblock %}{% block breadcrumbs %}{% endblock %}{% block content %}
{% if app_list %} {% for app in app_list %}
{% for model in app.models %}
{% if model.admin_url %}
{% else %}
{% endif %} {% if model.add_url %}
{% else %}
{% endif %} {% if model.admin_url %}
{% else %}
{% endif %}
{% endfor %}
{% blocktrans with name=app.name %}{
{ name }}{% endblocktrans %}
{ { model.name }} { { model.name }} {% trans 'Add' %}   {% trans 'Change' %}  
{% endfor %}{% else %}

{% trans "You don't have permission to edit anything." %}

{% endif %}
{% endblock %}
2、修改django.contrib.admin.options.py

修改:

action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')
为:

if settings.LOGGING != None:            action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')
修改:

from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )
修改:

from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )
修改:

from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )
3、在setting.py中设置Loging为None
LOGGING  = None#关闭后台日志记录功能
至此就可以用admin:111111登录后台管理远程的数据库了

转载地址:http://nwsmb.baihongyu.com/

你可能感兴趣的文章
【Django】Django web项目部署(Nginx+uwsgi)
查看>>
JS中原型链的理解
查看>>
oracle服务器和客户端字符集的查看和修改
查看>>
搭建服务器Apache+PHP+MySql需要注意的问题
查看>>
看完此文再不懂区块链算我输,用Python从零开始创建区块链
查看>>
C/S框架-WebService架构用户凭证(令牌)解决方案
查看>>
UVA 11149.Power of Matrix-矩阵快速幂倍增
查看>>
ajax post 请求415\ 400 错误
查看>>
jq关于对象类型的判断
查看>>
python--Websocket实现, 加密 sha1,base64
查看>>
c++ builder xe2 (Embarcadero rad studio) 远程调试 同样适用于 delphi 远程调试 教程
查看>>
洛谷 2921 记忆化搜索 tarjan 基环外向树
查看>>
0910
查看>>
IISExpress Log 文件路径
查看>>
P2787 语文1(chin1)- 理理思维
查看>>
Xshell配置ssh免密码登录-密钥公钥(Public key)
查看>>
2012年1月份第2周51Aspx源码发布详情
查看>>
PHP第三天!!黑人无表情 面向对象的特点等等!!
查看>>
2013年7月份第4周51Aspx源码发布详情
查看>>
Binary Tree Serialization and Deserialization
查看>>